package com.itany.shop.controller;


import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.sql.*;
import java.util.Random;

/**
 * @author 石小俊
 * @date 2023年07月04日 14:04
 */
@WebServlet("/showCode")
public class CodeServlet extends HttpServlet {
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Random random = new Random();
        // 在内存中定义一个画板
        BufferedImage image = new BufferedImage(50,25,BufferedImage.TYPE_INT_RGB);
        // 获取画板中对应的画笔
        Graphics graphics = image.getGraphics();
        // 指定画笔所填充的矩形区域
        graphics.fillRect(0,0,50,25);
        // 设置画笔的颜色,设置一个随机色
        graphics.setColor(new Color(random.nextInt(256),random.nextInt(256),random.nextInt(256)));
        // 设置画笔对应的字体样式
        graphics.setFont(new Font("宋体",Font.BOLD+Font.ITALIC,18));
        // 验证码内容,要求:随机数字或者英文字母
        String s = "0123456789qwertyuioplkjhgfdsazxcvbnm";
        StringBuffer buffer = new StringBuffer();
        for(int i = 0; i < 4; i++){
            buffer.append(s.charAt(random.nextInt(s.length())));
        }
        // 生成验证码之后需要与用户输入的验证码进行校验
        // 为了便于读取图片中的验证码内容
        // 在此处可以将验证码存放到session中
        request.getSession().setAttribute("code",buffer.toString());
        System.out.println("验证码:"+buffer);

        // 将随机生成的字符绘制到图片中
        graphics.drawString(buffer.toString(),5,18);
        // 输出图片
        ImageIO.write(image,"JPEG",response.getOutputStream());
    }


}
